//
//  ViewController.m
//  Enote
//
//  Created by Jack on 16/10/9.
//  Copyright © 2016年 Jack. All rights reserved.
//

#import "ViewController.h"
#import "EInputViewController.h"
#import "EnoteCell.h"
#import "EnoteModelFrame.h"

@interface ViewController ()<UICollectionViewDelegateFlowLayout,UICollectionViewDataSource,UICollectionViewDelegate>

@property (nonatomic, strong) UICollectionView * collectionView;
@property (nonatomic, strong) NSMutableArray   * dataSource;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"便签";
    _dataSource = [NSMutableArray array];
    UICollectionViewFlowLayout * layout = [[UICollectionViewFlowLayout alloc] init];
    
    layout.scrollDirection = UICollectionViewScrollDirectionVertical;
    self.collectionView = [[UICollectionView alloc] initWithFrame:self.view.bounds collectionViewLayout:layout];
    self.collectionView.backgroundColor = [UIColor hx_colorWithHexRGBAString:@"f5f5f5"];
    self.collectionView.dataSource = self;
    self.collectionView.delegate   = self;
    self.collectionView.showsVerticalScrollIndicator = NO;
    [_collectionView registerNib:[UINib nibWithNibName:@"EnoteCell" bundle:nil] forCellWithReuseIdentifier:@"EnoteCell"];
    [_collectionView registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"headerID"];
    [_collectionView registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:@"footerID"];
    
    [self.view addSubview:self.collectionView];
    
    self.collectionView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [self getDataFormSqlite];
    }];
    [self.collectionView.mj_header beginRefreshing];
    
    UIButton * button = [UIButton buttonWithType:UIButtonTypeSystem];
    UIImage * bgImage = [UIImage imageNamed:@"Icon_Add"];
    CGSize size = bgImage.size;
    [button setFrame:CGRectMake(SCREEN_WIDTH - size.width/2 - 50, SCREEN_HEIGHT - 50 - size.height / 2, size.width, size.height)];
    [button setBackgroundImage:bgImage forState:UIControlStateNormal];
    [button addTarget:self action:@selector(addEnote) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:button];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    [self getDataFormSqlite];
}
#pragma mark ---- UICollectionViewDataSource

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return 1;
}


- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    
    return _dataSource.count;
}


- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    EnoteModelFrame * frameModel = [_dataSource objectAtIndex:indexPath.item];

    Enote * model = frameModel.model;
    EnoteCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"EnoteCell" forIndexPath:indexPath];
    cell.eTitleTextView.text = [NSString stringWithFormat:@"%@",model.content];
    NSLog(@"%@",model.content);
    cell.timeLabel.text   = [KJTimeTransfer transferTimestamp:model.time toFormat:@"yyyy年MM月dd日 HH:mm"];
//    cell.backgroundColor = [UIColor blueColor];
    
    return cell;
}

// 和UITableView类似，UICollectionView也可设置段头段尾
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
{
    
    if([kind isEqualToString:UICollectionElementKindSectionHeader])
    {
        UICollectionReusableView *headerView = [_collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:@"headerID" forIndexPath:indexPath];
        if(headerView == nil)
        {
            headerView = [[UICollectionReusableView alloc] init];
        }
        headerView.backgroundColor = [UIColor grayColor];
        
        return headerView;
    }
    else if([kind isEqualToString:UICollectionElementKindSectionFooter])
    {
        UICollectionReusableView *footerView = [_collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:@"footerID" forIndexPath:indexPath];
        if(footerView == nil)
        {
            footerView = [[UICollectionReusableView alloc] init];
        }
        footerView.backgroundColor = [UIColor lightGrayColor];
        
        return footerView;
    }
    
    return nil;
}

- (BOOL)collectionView:(UICollectionView *)collectionView canMoveItemAtIndexPath:(NSIndexPath *)indexPath
{
    return YES;
}


- (void)collectionView:(UICollectionView *)collectionView moveItemAtIndexPath:(NSIndexPath *)sourceIndexPath toIndexPath:(NSIndexPath*)destinationIndexPath
{
    
}




#pragma mark ---- UICollectionViewDelegateFlowLayout

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    EnoteModelFrame * frameModel = [_dataSource objectAtIndex:indexPath.item];
    return CGSizeMake((SCREEN_WIDTH - 30) / 2, frameModel.size.height + 85.5 + 15);
    return (CGSize){(SCREEN_WIDTH - 30) / 2,SCREEN_WIDTH / 2};
}


- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
    return UIEdgeInsetsMake(10, 10, 10, 10);
}


- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section
{
    return (CGSize){SCREEN_WIDTH,44};
}


- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForFooterInSection:(NSInteger)section
{
    return CGSizeZero;
}




#pragma mark ---- UICollectionViewDelegate


// 点击高亮
- (void)collectionView:(UICollectionView *)collectionView didHighlightItemAtIndexPath:(NSIndexPath *)indexPath
{
    
}


// 选中某item
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    EInputViewController * ivc = [EInputViewController new];
    ivc.isInput = YES;
    [self.navigationController pushViewController:ivc animated:YES];
}

#pragma mark - didReceiveMemoryWarning
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    self.collectionView = nil;
}

#pragma mark - 读取数据
- (void)getDataFormSqlite {
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        [self.manage readAllDataModel:^(NSArray *modelArray) {
            
            NSMutableArray * tempArr = [NSMutableArray arrayWithCapacity:modelArray.count];
            
            for (Enote * model  in modelArray) {
                EnoteModelFrame * modelFrame = [[EnoteModelFrame alloc] initWithModel:model];
                [tempArr addObject:modelFrame];
            }
            
            
            dispatch_async(dispatch_get_main_queue(), ^{
                _dataSource = [NSMutableArray arrayWithArray:tempArr];
                [_collectionView reloadData];
                [self.collectionView.mj_header endRefreshing];
            });
        } fail:^(NSError *error) {
            dispatch_async(dispatch_get_main_queue(), ^{
                [self.collectionView.mj_header endRefreshing];
            });
        }];
    });

}

#pragma mark - 添加便签

- (void)addEnote {
    EInputViewController * ivc = [EInputViewController new];
    ivc.isInput = YES;
    [self.navigationController pushViewController:ivc animated:YES];
}

@end
